package web

import (
	"DeviceManager/storage"
	"encoding/json"
	"net/http"
	"time"
)

var loginAttempts = make(map[string]int)
var lockoutTime = time.Minute * 5
var lockoutEnd = make(map[string]time.Time)

// var captchaText = generateCaptchaText()

// func generateCaptchaText() string {
// 	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// 	b := make([]byte, 6)
// 	for i := range b {
// 		b[i] = charset[rand.Intn(len(charset))]
// 	}
// 	return string(b)
// }

func loginHandler(w http.ResponseWriter, r *http.Request) {
	var credentials struct {
		Username string `json:"username"`
		Password string `json:"password"`
		Captcha  string `json:"captcha"`
	}

	if err := json.NewDecoder(r.Body).Decode(&credentials); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	ip := r.RemoteAddr
	if lockoutEnd[ip].After(time.Now()) {
		http.Error(w, "Too many failed attempts. Try again later.", http.StatusTooManyRequests)
		return
	}

	// if credentials.Captcha != captchaText {
	// 	http.Error(w, "Invalid captcha", http.StatusUnauthorized)
	// 	captchaText = generateCaptchaText()
	// 	return
	// }

	if credentials.Username == "admin" && credentials.Password == "123456" {
		loginAttempts[ip] = 0
		w.WriteHeader(http.StatusOK)
	} else {
		loginAttempts[ip]++
		if loginAttempts[ip] >= 3 {
			lockoutEnd[ip] = time.Now().Add(lockoutTime)
			loginAttempts[ip] = 0
		}
		http.Error(w, "Invalid credentials", http.StatusUnauthorized)
	}
}

func deviceHandler(w http.ResponseWriter, r *http.Request) {
	devices, err := storage.LoadDevices()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(devices)
}

func configHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodPost {
		var newConfig storage.Config
		if err := json.NewDecoder(r.Body).Decode(&newConfig); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		if err := storage.SaveConfig(newConfig); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
	} else {
		config, err := storage.LoadConfig()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		json.NewEncoder(w).Encode(config)
	}
}
